use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader};

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Response {
    message: Message,
    done: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Message {
    role: String,
    content: String,
}
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
use tokio;


#[derive(Serialize)]
struct ChatCompletionRequest {
    model: String,
    messages: Vec<Message>,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 设置请求 URL 和头部
    let url = "https://spark-api-open.xf-yun.com/v1/chat/completions";
    let token = "Bearer 123"; // 注意此处替换自己的APIPassword

    // 创建请求体
    let request_body = ChatCompletionRequest {
        model: "general".to_string(),
        messages: vec![Message {
            role: "user".to_string(),
            content: "你是谁".to_string(),
        }],
    };

    // 创建客户端并发送 POST 请求
    let client = reqwest::Client::new();
    let response = client
        .post(url)
        .header(AUTHORIZATION, token)
        .header(CONTENT_TYPE, "application/json")
        .json(&request_body)
        .send()
        .await?;

    // 检查响应状态码
    if response.status().is_success() {
        // 获取响应文本并打印
        let text = response.text().await?;
        println!("Response: {}", text);
    } else {
        // 如果请求失败，打印详细的错误信息
        eprintln!("请求失败: {:?}", response);

        // 打印响应头
        let headers = response.headers();
        for (name, value) in headers.iter() {
            eprintln!("Header: {} - {}", name, value.to_str().unwrap_or("无法解析"));
        }

        // 打印响应体
        let text = response.text().await?;
        eprintln!("Response Body: {}", text);
    }

    Ok(())
}
//#[tokio::main]
async fn hello_ollama() -> Result<(), Box<dyn std::error::Error>> {
    let mut messages: Vec<Message> = vec![];
    let client = reqwest::Client::new();

    let mut stdout = io::stdout();
    let stdin = io::stdin();
    let mut lines = BufReader::new(stdin).lines();

    stdout.write_all(b"\n> ").await?;
    stdout.flush().await?;
    while let Some(line) = lines.next_line().await? {
        if !line.is_empty() {
            messages.push(Message {
                role: String::from("user"),
                content: line,
            });

            let mut res = client
                .post("http://127.0.0.1:11434/api/chat")
                .json(&json!({
                    "model": "qwen2",
                    "messages": &messages

                }))
                .send()
                .await?;

            let mut message = String::default();
            while let Some(chunk) = res.chunk().await? {
                if let Ok(resp_part) = serde_json::from_slice::<Response>(&chunk) {
                    if !resp_part.done {
                        stdout
                            .write_all(resp_part.message.content.as_bytes())
                            .await?;
                        stdout.flush().await?;

                        message.push_str(&resp_part.message.content);
                    }
                }
            }

            if !message.is_empty() {
                messages.push(Message {
                    role: String::from("assistant"),
                    content: message,
                });
            }
        }

        stdout.write_all(b"\n> ").await?;
        stdout.flush().await?;
    }

    Ok(())
}
